package com.liwbn.rbac.controller;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.liwbn.rbac.exception.JsonReException;
import com.liwbn.rbac.model.Permission;
import com.liwbn.rbac.service.PermissionService;
import com.liwbn.rbac.support.ExceptionCode;
import com.liwbn.rbac.support.JsonReInfo;

/**
 * 模块权限管理
 * 
 * @author liwb 2016年3月4日 下午6:51:24
 */
@Controller
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    /**
     * 页面展示
     * 
     * @return
     */
    @RequestMapping("/system/modm")
    public String showPage() {
        return "system/modm";
    }

    @RequestMapping("/system/getAllModule")
    @ResponseBody
    public String getAllMenus() {
        List<Permission> module;
        try {
            module = permissionService.selectAll();
        } catch (Exception e) {
            throw new JsonReException(101, ExceptionCode.CODE_101_EXCEPTION, e);
        }
        return new JsonReInfo(100, module).toString();
    }

    /**
     * 根据客户端提交信息修改菜单
     * 
     * @param permission
     *            格式: [[a][u][d]]
     * @return
     */
    @RequestMapping("/system/changeModule")
    @ResponseBody
    public String parseModule(String permission) {
        try {
            if (StringUtils.isNotBlank(permission)) {
                ObjectMapper om = new ObjectMapper();
                List<List<Permission>> tempFrame = om.readValue(permission,
                        new TypeReference<List<List<Permission>>>() {
                        });
                if (tempFrame.size() == 3) {
                    permissionService.updateByJSONModule(tempFrame);
                }
                return new JsonReInfo(100, ExceptionCode.CODE_100_EXCEPTION)
                        .toString();
            } else {
                return new JsonReInfo(102, ExceptionCode.CODE_102_EXCEPTION)
                        .toString();
            }
        } catch (Exception e) {
            throw new JsonReException(101, ExceptionCode.CODE_101_EXCEPTION, e);
        }
    }
}
